'use strict';

const Controller = require('egg').Controller;
const svgCaptcha = require('svg-captcha');
const crypto = require("crypto");


class UserController extends Controller {
    async edit() {
        const { ctx, app } = this
        const { id, depart_id, phone, pwd, avatar, name, status } = ctx.request.body
        ctx.validate({
            depart_id: {
                type: 'int',
                required: true,
                desc: '部门id'
            },
            phone: {
                type: 'phone',
                required: true,
                desc: '手机号'
            },
            pwd: {
                type: 'string',
                required: false,
                desc: '密码'
            },
            avatar: {
                type: 'string',
                required: false,
                desc: '头像'
            },
            name: {
                type: 'string',
                required: true,
                desc: '昵称'
            },
            status: {
                type: 'string',
                required: true,
                range: {
                    in: ['0', '1', '2']
                },
                desc: '状态'
            },
        })
        let oneList, twoList

        if (! await app.model.AdminDepart.findByPk(depart_id)) {
            ctx.throw(400, '部门不存在')
        }
        if (id == 0) {//新建
            let ll = await app.model.AdminUser.findOne({ where: { phone } })
            // return
            if (ll) {
                ctx.throw(400, '手机号已存在')
            }
            twoList = await app.model.AdminUser.create({
                depart_id, phone, pwd, avatar, name, status
            })
        } else {//编辑
            oneList = await app.model.AdminUser.findByPk(id)
            if (!oneList) {
                ctx.throw(400, '数据不存在')
            }
            twoList = await oneList.update({ depart_id, phone, avatar, name, status })
        }
        ctx.apiSuccess(twoList)
    }
    async list() {
        const { ctx, app } = this
        let { name, depart_id, phone } = ctx.query
        let where = {}
        let Op = app.Sequelize.Op;
        if (name != "" && name != undefined) {
            where.name = {
                [Op.like]: '%' + name + '%'
            }
        }
        if (depart_id != "" && depart_id != undefined) {
            where.depart_id = depart_id
        }
        if (phone != "" && phone != undefined) {
            where.phone = phone
        }
        let oneList = await ctx.page(app.model.AdminUser, where)
        ctx.apiSuccess(oneList)
    }
    async del() {
        const { ctx, app } = this
        ctx.validate({
            id: {
                type: 'int',
                required: true,
                desc: 'id'
            }
        })
        let id = ctx.query.id
        let oneList = await app.model.AdminUser.findByPk(id)
        if (!oneList) {
            ctx.throw(400, '数据不存在')
        }
        oneList = await oneList.destroy()
        if (!oneList) {
            ctx.throw(400, '操作失败')
        }
        ctx.apiSuccess('删除成功')
    }
    // 设置 权限
    async setpower() {
        const { ctx, app } = this
        const { id, nav_id, btn_id } = ctx.request.body
        ctx.validate({
            id: {
                type: 'int',
                required: true,
                desc: '员工id'
            },
            nav_id: {
                type: 'string',
                required: true,
                desc: '导航拦id'
            },
            btn_id: {
                type: 'string',
                required: true,
                desc: '按钮id'
            }
        })
        let oneList
        oneList = await app.model.AdminUser.findByPk(id)
        if (!oneList) {
            ctx.throw(400, '员工数据不存在')
        }
        let navIdList = nav_id.split(',')

        let navList = await app.model.AdminNav.findAll({
            where: {
                id: navIdList
            }
        })
        if (navList.length !== navIdList.length) {
            ctx.throw(400, '导航栏id组数据不正确')
        }
        let btnIdList = btn_id.split(',')

        let btnList = await app.model.AdminBtn.findAll({
            where: {
                id: btnIdList
            }
        })
        if (btnList.length !== btnIdList.length) {
            ctx.throw(400, '按钮id组数据不正确')
        }
        oneList.update({ nav_id, btn_id })
        ctx.apiSuccess('设置成功')
    }
    //图片验证码
    async captcha() {
        const { ctx, service } = this
        const captcha = svgCaptcha.createMathExpr({
            size: 4,
            fontSize: 50,
            ignoreChars: 'Ooli',
            width: 100,
            height: 40,
            noise: 3,
            color: true,
            background: '#ffd',
        });
        service.cache.set('captcha', captcha.text, 60)
        console.log(captcha.text)
        ctx.response.type = 'image/svg+xml';
        ctx.body = captcha.data;
    }

    //登陆
    async login() {
        const { ctx, app, service } = this
        const { phone, pwd, imageCode } = ctx.request.body
        ctx.validate({
            phone: {
                type: 'phone',
                required: true,
                desc: '手机号'
            },
            pwd: {
                type: 'string',
                required: true,
                desc: '密码'
            }
        })
        let oneList = await app.model.AdminUser.findOne({
            where: {
                phone
            }
        })
        if (!oneList) {
            ctx.throw(400, '手机号错误!')
        }
        const hmac = crypto.createHash("sha256", app.config.crypto.secret);
        hmac.update(pwd);
        let hash = hmac.digest("hex");
        if (oneList.pwd != hash) {
            ctx.throw(400, '密码错误')
        }
        let token = ctx.getToken(JSON.stringify({ id: oneList.id, name: oneList.name, phone: oneList.phone, status: oneList.status }))
        oneList.update({token})
        ctx.apiSuccess(token)
    }
    // 获取用户信息
    async userInfo() {
        const { ctx, app } = this
        const admin_id = ctx.adminUser.id
        let oneList = await app.model.AdminUser.findOne({
            where: {
                id: admin_id
            },
            include: [
                {
                    model: app.model.AdminDepart
                }]
        })
        let navList = await app.model.AdminNav.findAll({
            where: {
                id: oneList.nav_id && oneList.nav_id.length ? oneList.nav_id.split(',') : []
            }
        })
        let btnList = await app.model.AdminBtn.findAll({
            where: {
                id: oneList.btn_id && oneList.btn_id.length ? oneList.btn_id.split(',') : []
            }
        })
        ctx.apiSuccess({ oneList, navList, btnList })
    }
    //微信 用户列表
    async wxuserlist() {
        const { ctx, app } = this
        let { nickname, role, start_time, end_time } = ctx.query
        let where = {}, Op = app.Sequelize.Op;
        if (nickname != '' && nickname != undefined) {
            where.nickname = nickname
        }
        if (role != '' && role != undefined) {
            where.role = role
        }
        if (start_time != '' && start_time != undefined || end_time != '' && end_time != undefined) {
            where = {
                [Op.and]: [
                    {
                        created_at: {
                            [Op.gt]: start_time
                        }
                    },
                    { created_at: { [Op.lt]: end_time } }
                ]
            }
        }
        console.log(where)

        let oneList = await ctx.page(app.model.WxUser, where)
        ctx.apiSuccess(oneList)
    }
    //修改 密码
    async repwd() {
        const { ctx, app } = this
        const adminuser = ctx.adminUser
        let { pwd } = ctx.request.body
        ctx.validate({
            pwd: {
                type: 'string',
                required: true,
                desc: '密码'
            }
        })
        let list = await app.model.AdminUser.findByPk(adminuser.id)
        if (!list) {
            ctx.throw(400, '数据不存在')
        }
        let one = await list.update({ pwd })
        if (!one) {
            ctx.throw(400, '修改失败')
        }
        ctx.apiSuccess('修改成功')
    }
}

module.exports = UserController;
